package ccnu.agile.service.impl;

import ccnu.agile.bean.request.FileRequest;
import ccnu.agile.bean.response.MapDataResponse;
import ccnu.agile.bean.response.Response;
import ccnu.agile.config.oss.OSSConfig;
import ccnu.agile.service.IFOSService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Description: 阿里云OSS服务类
 * @Author: JreamY
 * @Date: 2021/11/25
 **/
@Service
public class OSSServiceImpl implements IFOSService {

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private OSS oss;

    @Override
    public Response upload(FileRequest fileRequest) {

        String saveFileName = getSaveFileName(fileRequest);
        try {
            PutObjectRequest request = new PutObjectRequest(ossConfig.getBucketName(), saveFileName, fileRequest.getFile().getInputStream());
            oss.putObject(request);
        } catch (IOException e) {
            e.printStackTrace();
        }

        MapDataResponse response = MapDataResponse.newSuccess(true)
                .put("url", ossConfig.getUrlPrefix() + saveFileName);

        return response;
    }
}
